<template>
  <div class="app-container" v-loading="dialogVisible">
    <!-- <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" @close="closeTag"> -->
    <div style="display:flex;justifyContent:center;">
      <parser :form-conf="formConfData" :tableName="tableName" @submit="submit" status="add" :originData="originData" :key="time" ref="parser"
        v-if="!dialogVisible" style="width:80%;" @reset="reset" @cancel="closeTag"/>
    </div>
    <!-- </el-dialog> -->
  </div>
</template>
<script>
  import Parser from './parser'
  import {
    getFormInfo,
    insertData,
    updateData
  } from '@/api/custom/formDesigner'
  import { createProcessInstance } from "@/api/bpm/processInstance";
  import { getProcessIn } from "@/api/custom/formPoster";
  const arrTypes = ['cascader', 'checkbox', 'time-range', 'date-range','tree-table'];
  export default {
    name: 'formsubmit',
    components: {
      Parser
    },
    data() {
      return {
        dialogVisible: true,
        formConfData: {}, //表单配置
        tableName: '', //表名
        dialogTitle: '', //弹窗名
        fieldData: [], //表字段
        originData: {},
        time: '',
        formId: '',
        variables: {},
        tagIcons: []
      }
    },
    mounted() {
      // if (this.$route.params.formName) {
      //   this.$route.meta.title = this.$route.params.formName
      //   this.dialogTitle = this.$route.params.formName
      // } else {
      //   this.dialogTitle = this.$route.name
      // }
      this.getFormDetail()
    },
    methods: {
      //获取表单详情
      getFormDetail() {
        let path = this.$route.path.split('/')
        getFormInfo(path[path.length - 1]).then((res) => {
          if (res.code === 0) {
            this.formId = res.data.id
            this.tableName = res.data.tableName
            this.formConfData = JSON.parse(res.data.formJsonUser)
            this.getTagIcons(this.formConfData.fields)
            this.fieldData = JSON.parse(res.data.formJsonData).data
            this.time = new Date().getMilliseconds()
            this.dialogVisible = false
          }
        }).catch(e => console.log(e))
      },
      //数据格式化成对应数据库存储类型
      getFormatValue(data, tag, format) {
        if (arrTypes.includes(tag)) { //组件数据类型为数组
          return data.toString()
        }
        if (tag === 'upload') {
          return JSON.stringify(data)
        }
        if ((format === 'int' || format === 'double' ||format === 'decimal') && !Number.isNaN(data)) { //数据库存储类型为int或double，但组件数据类型为字符串
          if(tag === "number"){
            return data!==''?data:''
          }
          return data!==''?Number(data):''
        }
        if (format === 'varchar') {
          return data.toString()
        }
        return data
      },
      getTagIcons(data) {
        if (data.length === 0) return
        data.filter((item) => {
          return item.__config__.tag !== 'TitleLine'
        }).map((item) => {
          if (item.__config__.tag === 'el-tabs' || item.__config__.tag === 'Steps'|| item.__config__.tag === 'el-collapse') {
            let tem = item.__config__.children.map((c) => {
              this.getTagIcons(c.__config__.children)
            })
          } else {
            this.tagIcons.push(item.__config__.tagIcon)
          }
        })
      },
      //提交数据
      submit(data) {
        let fields = []
        this.fieldData.map((item, index) => {
          if (data[item.name] !== undefined && data[item.name] !== null) {
            let value = this.getFormatValue(data[item.name], this.tagIcons[index], item.format)
            fields.push({
              name: item.name,
              type: item.format,
              value: value
            })
          }
        })
      this.variables = data
        insertData({
          tableName: this.tableName,
          dataType: '1',
          data: fields
        }).then((res) => {
          if (res.code === 0) {
            const data = res.data
            getProcessIn(this.formId).then((res) => {
                if(res.data){ //关联实例
                  createProcessInstance({
                    formId: this.formId,
                    formRecordId: data,
                    variables: this.variables
                  }).then(res => {})
                  this.$message.success('提交成功')
                  this.$refs.parser.resetForm()
                  // this.time = new Date().getMilliseconds()
                }else{
                  this.$message.success('提交成功')
                  this.$refs.parser.resetForm()
                  // this.time = new Date().getMilliseconds()
                }
            })
          }
        }).catch(e => console.log(e))
      },
      reset() {
        this.time = new Date().getMilliseconds()
      },
      //关闭标签
      closeTag() {
        this.$store.dispatch('tagsView/delView', this.$route).then(({
          visitedViews
        }) => {
          this.toLastView(visitedViews, this.$route)
        })
      },
      //跳转到上一页
      toLastView(visitedViews, view) {
        const latestView = visitedViews.slice(-1)[0]
        if (latestView) {
          this.$router.push(latestView.fullPath)
        } else {
          if (view.name === 'Dashboard') {
            this.$router.replace({
              path: '/redirect' + view.fullPath
            })
          } else {
            this.$router.push('/')
          }
        }
      },
    }
  }

</script>
